<template>
	<view class="bg-light" style="height: 100%">
		<!-- 轮播主图 -->
		<scroll-view @scroll="scroll" scroll-y="true" :scroll-into-view="scrollIntoViewId" class="w-100" :style="'height:calc(100vh - 110rpx) '">
			<view id="top" style="position: relative">
				<swiper id="swiper" :autoplay="true" :interval="3000" :duration="500" circular
					:style="{ height: swiperWidth + 'px' }" @change="changeIndicatorDots">
					<swiper-item v-for="(item, index) in Swiper" :key="index">
						<image @click="showPicture(item.Picture_URL)" v-if="BASE_IMG" :src="BASE_IMG + item.Picture_URL" mode="sapectFill" :style="{ height: swiperWidth + 'px', width: '100%' }" :lazy-load="true"></image>
					</swiper-item>
				</swiper>
				<text class="rounded-circle font-sm px-2 text-white current">{{ current }}</text>
			</view>
			<!-- 商品详情 -->
			<view class="pt-3 pb-3 bg-white rounded-lg mx-3 shadow" style="position: relative; margin-top: -30rpx;">
				<view class="mx-3 flex flex-column ">
					<text class="mb-2 font-lg font-weight-bold">{{Article.Article_Name}}</text>
					<text class="mb-2 font-sm text-muted">商品规格:{{Specifications.Specifications_Name}}</text>
					<!-- 活动信息 -->
					<view v-if="form.Activity_SerialNumber&&Activity.Activity_SerialNumber" class="flex flex-column">
						<view  class="mb-2 flex justify-between align-end">
							<view class="font w-100 text-ellipsis">{{Activity.Activity_Name}}</view>
							<view class="flex-shrink flex align-center">
								<text class="font-small" style="color:rgb(236,23,17);">剩余:</text>
								<uni-countdown update :font-size="10" splitor-color="rgb(236,23,17)" color="rgb(236,23,17)" :day="timer.d" :hour="timer.h" :minute="timer.m" :second="timer.s" ></uni-countdown>
							</view>
						</view>
						<view v-if="Activity.Cash_Point=='0'">
							<uni-collapse>
								<uni-collapse-item border="none" titleBorder="none" :showArrow="false">
									<template v-slot:title>
										<view class="flex justify-between align-center py-1">
											<text class="font-sm text-success">{{Activity.Deduction_Type=='0'?"可用积分不超过"+Activity.Deduction_Limit:"可用积分不超过该商品总金额"+Activity.Deduction_Limit+"%"}}</text>
											<text class="font-sm text-muted">详情</text>
										</view>
									</template>
									<!-- <view class="flex justify-between align-center py-1">
										<text class="font-sm font-weight-bold">单价</text>
										<money color="#000" :money="Sales_Unit_Price"></money>
									</view>
									<view class="flex justify-between align-center py-1">
										<text class="font-sm font-weight-bold">积分抵扣</text>
										<money color="#dc3545" before="减" :money="item.Deduction"></money>
									</view> -->
								</uni-collapse-item>
							</uni-collapse>
						</view>
					</view>
					<view class="my-2 flex justify-between align-end">
						<text class="font-sm text-success">剩余数量:{{Specifications.Stock_Remain}}</text>
						<text class="font-lg">￥{{Sales_Unit_Price}}</text>
					</view>
				</view>
			</view>
			<!-- 其它规格 -->
			<!-- <view v-if="Article.article_specifications.length > 1" class="pt-3 pb-3 bg-white rounded-lg mx-3 shadow mt-3">
				<text class="h3 font-weight-bold ml-3">规格</text>
				<view class="mx-3 flex flex-wrap mt-3">
					<view @click="changeTab(index)" :class="index===active?'text-white bg-success':'text-success'" class="font px-1 mr-1 border border-success rounded" v-for="(item,index) in Article.article_specifications" :key="index">
						{{item.Specifications_Name}}
					</view>
				</view>
			</view> -->
			<view v-if="business_article_group.length > 0" class="pt-2 pb-3 bg-white rounded-lg mx-3 shadow mt-3">
				<view class="mt-1" v-for="(obj,id) in business_article_group" :key="id">
					<text class="font font-weight-bold ml-3">{{obj.Specification_Group_Name}}</text>
					<view class="mx-3 flex flex-wrap mt-1">
						<view @click="changeTab(obj,item)" :class="item.isSelect?'text-white bg-success':'text-success'" class="font-sm px-1 mr-1 border border-success rounded" v-for="(item,index) in obj.Children.business_article_group_detail" :key="index">
							{{item.Specification_Group_Detail_Name}}
						</view>
					</view>
				</view>
			</view>
			<!-- 商品详情图 -->
			<view class="mx-3 mt-3 pt-3 pb-3 rounded-lg bg-white mb-3 shadow">
				<text class="h3 font-weight-bold ml-3 mb-3">商品详情</text>
				<view class="flex flex-column mx-3">
					<image @click="showPicture(item.Picture_URL)" v-if="BASE_IMG" v-for="(item, index) in Detail" :key="index" class="w-100" :src="BASE_IMG + item.Picture_URL" mode="widthFix" :lazy-load="true"></image>
				</view>
			</view>
		</scroll-view>
		<!-- 底部按钮 -->
		<view class="fixed-bottom shadow flex align-center justify-between bg-white" style="height: 110rpx;">
			<view class="flex" style="justify-content: space-around; width: 30%;">
				<view @click="handleBtn('index')" class="flex flex-column justify-center align-center">
					<uni-icons type="home" size="18"></uni-icons>
					<text class="font-sm text-muted">首页</text>
				</view>
				<!-- <view class="flex flex-column justify-center align-center">
					<uni-icons type="chat" size="18"></uni-icons>
					<text class="font-sm text-muted">客服</text>
					<button id="shareBtn" class="rounded-circle" open-type="contact">
						客服
					</button>
				</view> -->
			</view>
			<view class="flex" style="width: 70%;">
				<view @click="handleBuy('car')" class="mx-3 w-100 bg-success px-3 py-2 rounded-circle flex justify-center">
					<text class="text-white font">加入购物车</text>
				</view>
				<view @click="handleBuy('buy')" class="mr-3 w-100 bg-success px-3 py-2 rounded-circle flex justify-center">
					<text class="text-white font">立即购买</text>
				</view>
			</view>
		</view>
		<!-- 右侧悬浮按钮 -->
		<view class="flex position-fixed flex-column" style="right: 30rpx; bottom: 230rpx;">
			<view class="shadow mt-2 bg-white rounded-circle flex justify-center align-center position-relative"
				style="width: 100rpx; height: 100rpx;" @click="handleBtn(item.title)" 
				v-if="item.isShow" v-for="(item, index) in btn" :key="index">
				<i v-if="item.title == 'car' && shopNum > 0" class="bg-danger rounded-circle text-white px-1"
					style="position: absolute; top: -5rpx; left: -5rpx; font-size: 12px;">{{ shopNum }}</i>
				<uni-icons :type="item.icon" size="24"></uni-icons>
				<button id="shareBtn" class="rounded-circle" open-type="share" v-if="item.title == 'share'">
					分享
				</button>
				<button id="shareBtn" class="rounded-circle" open-type="contact" v-if="item.title == 'serve'">
					客服
				</button>
			</view>
		</view>
		<!-- 遮罩层和弹窗 -->
		<popUp :show="showMask" @Close="()=>{this.showMask=!this.showMask}" @submit1="submitForm" :button="[mask=='buy'?'提交订单':'加入购物车']" Height="80">
			<view class="mx-3 pt-3 flex align-end">
				<view class=" rounded-lg overflow-hidden shadow" style="width: 150rpx; height: 150rpx;">
					<image v-if="BASE_IMG" style="width: 100%;height: 100%;" :src="BASE_IMG + Specifications.Picture_URL" mode="scaleToFill"></image>
				</view>
				<text class="font-lg ml-3">￥{{Sales_Unit_Price}}</text>
			</view>
			<!-- 地址选择 -->
			<view @click="onAddress()" class="mx-3 mt-3 px-2 py-3 bg-white rounded flex align-center ">
				<view class="flex align-center w-100">
					<uni-icons class="flex-shrink mr-2" fontFamily="iconfont" color="#28a745" size="20">{{'\ue616'}}</uni-icons>
					<view v-if="customerAddress" class="flex flex-column w-100">
						<text class="font">{{customerAddress.Province}}{{customerAddress.City}}{{customerAddress.County}}{{customerAddress.Details}}</text>
						<text class="mt-2 font-sm text-muted">{{customerAddress.Name}} {{customerAddress.Phone}}</text>
					</view>
					<text v-else class="font pr-2">新建地址</text>
				</view>
				<uni-icons class="flex-shrink mr-2" type="right" size="16"></uni-icons>
			</view>
			<!-- 其它规格 -->
			<!-- <view v-if="Article.article_specifications.length > 1" class="pt-3 pb-3 bg-white rounded-lg mx-3 mt-3">
				<text class="font font-weight-bold ml-3 ">其它规格</text>
				<view class="mx-3 flex flex-wrap mt-2">
					<view @click="changeTab(index)" :class="index===active?'text-white bg-success':'text-success'" class="font-sm px-1 mr-1 border border-success rounded" v-for="(item,index) in Article.article_specifications" :key="index">
						{{item.Specifications_Name}}
					</view>
				</view>
			</view> -->
			<view v-if="business_article_group.length > 0" class="pt-2 pb-3 bg-white rounded-lg mx-3 shadow mt-3">
				<view class="mt-1" v-for="(obj,id) in business_article_group" :key="id">
					<text class="font font-weight-bold ml-3">{{obj.Specification_Group_Name}}</text>
					<view class="mx-3 flex flex-wrap mt-1">
						<view @click="changeTab(obj,item)" :class="item.isSelect?'text-white bg-success':'text-success'" class="font-sm px-1 mr-1 border border-success rounded" v-for="(item,index) in obj.Children.business_article_group_detail" :key="index">
							{{item.Specification_Group_Detail_Name}}
						</view>
					</view>
				</view>
			</view>
			<!-- 选择数量 -->
			<view class="flex justify-between align-center pt-3 pb-3 bg-white rounded-lg mx-3 mt-3">
				<text class="font font-weight-bold ml-3 ">数量</text>
				<counter class="mr-3" v-model="Quantity" :loading="loading"></counter>
			</view>
		</popUp>
		<view v-if="Picture_URL" @click="()=>{this.Picture_URL = ''}" class="mask flex align-center" style="background-color: black;">
			<image style="width: 100%;" :src="BASE_IMG +Picture_URL" mode="widthFix"></image>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import { mapState, mapMutations } from 'vuex';
	import Base64 from "base-64";
	import { getArticleDescription } from "@/api/article.js"
	import { generalQueryByTableName,generalQueryBySQLSerialNumber,generalSave,getSubtableInquiry } from "@/api/generalBusiness.js"
	import { addShoppingTrolley } from "@/api/salerOrder.js"
	import { shoppingTrolleyJSON } from "@/static/js/OrderUtil.js"
	import { getCountDown,DateTime } from "@/static/js/DateUtil.js"
	import {ShopCartQuantity} from "./js/ShopCartQuantity.js";
	import money from "@/components/tool/money.vue";
	import popUp from "@/components/tool/pop-up.vue";
	import counter from "@/components/tool/counter.vue";
	export default {
		components:{
			money,
			popUp,
			counter
		},
		mixins:[ShopCartQuantity],
		data() {
			return {
				timer:{d:0,h:0,m:0,s:0},//倒计时
				scrollIntoViewId:'',
				swiperWidth: 0, //自适应轮播组件长度
				scrollTop:0,//滚动距离
				active:0,//已选规格
				current: "", //轮播图数
				customerAddress: null, //默认地址
				form:{
					Supplier_Article_SerialNumber:'',
					Activity_SerialNumber:'',
				},
				Article:{
					Swiper:[],
					Detail:[],
					article_specifications:[{
						Chlidren:{
							Deduction_Type:'',
							Deduction_Limit:''
						}
					}],
				},
				business_article_group:[],
				Quantity:1,//购买数量
				btn: [{
						//右侧悬浮按钮
						title: "top",
						icon: "up",
						isShow: false,
					},
					{
						title: "serve",
						icon: "chat",
						isShow: true,
					},
					{
						title: "car",
						icon: "cart",
						isShow: true,
					},
					{
						title: "share",
						icon: "redo",
						isShow: true,
					},
				],
				mask:'',//枚举
				showMask:false,//弹窗
				loading:false,
				Picture_URL:'',
			};
		},
		onShow() {
			if (uni.getStorageSync("customerAddress")) {
				this.customerAddress = uni.getStorageSync("customerAddress");
			}
		},
		onLoad(options) {
			this.form.Supplier_Article_SerialNumber = options.Supplier_Article_SerialNumber;
			if (options.Activity_SerialNumber) {//活动页
				this.form.Activity_SerialNumber = options.Activity_SerialNumber;
			}
			this.getData(this.form,(data)=>{
				if(data.length == 1){
					//设置默认规格
					data[0].article_specifications.forEach((item,index)=>{
						if(item.Article_Specifications_SerialNumber == options.Article_Specifications_SerialNumber){
							this.active = index;
						}
					})
					//浏览记录保存
					this.browsingHistory();
				}
			});
			this.carouselChart();
			//浏览记录
		},
		computed: {
			...mapState(['Open_ID','App_ID','BASE_IMG','HOME_Page','shopNum']),
			Swiper(){//冒泡排序处理轮播图		
				for (var i = 0; i < this.Article.Swiper.length - 1; i++) {
					for (var j = 0; j < this.Article.Swiper.length - i - 1; j++) {
						if (parseInt(this.Article.Swiper[j].Picture_Order) > parseInt(this.Article.Swiper[j + 1].Picture_Order)) {
							var count = this.Article.Swiper[j];
							this.Article.Swiper[j] = this.Article.Swiper[j + 1];
							this.Article.Swiper[j + 1] = count;
						};
					};
				};
				return this.Article.Swiper		
			},
			Detail(){//冒泡排序处理详情图
				for (var i = 0; i < this.Article.Detail.length - 1; i++) {
					for (var j = 0; j < this.Article.Detail.length - i - 1; j++) {
						if (parseInt(this.Article.Detail[j].Picture_Order) > parseInt(this.Article.Detail[j + 1].Picture_Order)) {
							var count = this.Article.Detail[j];
							this.Article.Detail[j] = this.Article.Detail[j + 1];
							this.Article.Detail[j + 1] = count;
						};
					};
				};
				return this.Article.Detail	
			},
			Specifications(){//当前规格
				let str = "";
				this.business_article_group.forEach(item=>{
					if(str){
						str= str + "-" + item.Children.business_article_group_detail.filter(i=>i.isSelect)[0].Specification_Group_Detail_Name
					}else{
						str = item.Children.business_article_group_detail.filter(i=>i.isSelect)[0].Specification_Group_Detail_Name
					}
				})
				return this.Article.article_specifications.filter(i=>i.Specifications_Name == str)[0]
			},
			Activity(){//活动信息
				try{
					return this.Specifications.Children
				}catch(e){
					return {}
				}
			},
			Sales_Unit_Price(){//销售价格
				try{
					if(this.form.Activity_SerialNumber){//活动
						return this.Activity.Activity_Unit_Price
					}else{//正常
						return this.Specifications.Sales_Unit_Price
					}
				}catch(e){
					return '';
				}	
			},
		},
		methods: {
			...mapMutations(['setBASEPath','setBASEQuery','modifyShopNum']),
			showPicture(val){
				this.Picture_URL = val
			},
			async getData(form,callback){
				let data = await getArticleDescription(form)
				if(data&&data.length == 1){
					let { business_article_group } = await getSubtableInquiry({
						Primary_Key:data[0].Article_SerialNumber,
						JSONObject:JSON.stringify({business_article_group: {business_article_group_detail:{}}})
					})
					
					business_article_group.forEach(item=>{
						item.Children.business_article_group_detail = item.Children.business_article_group_detail.filter(i=>data[0].article_specifications.some(x=>x.Specifications_Name==i.Specification_Group_Detail_Name))
						item.Children.business_article_group_detail.forEach((ite,index)=>{
							ite.isSelect = (index==0?true:false);
						})
					}) 
					this.business_article_group = business_article_group;
					//判断是否活动商品
					this.Article = data[0];
					this.current = "1/"+this.Article.Swiper.length
					if(this.form.Activity_SerialNumber){
						this.countTimer();
					}
				}
				callback?callback(data):null;
			},
			async browsingHistory(){//
				//将该商品信息添加到浏览日志中
				let business_browsing_history = [{
					Browsing_History_SerialNumber:'',
					Open_ID:this.Open_ID,
					Supplier_Article_SerialNumber:this.Specifications.Supplier_Article_SerialNumber,
					Activity_SerialNumber:this.form.Activity_SerialNumber,
					Article_Name:this.Article.Article_Name,
					Brand_SerialNumber:this.Article.Brand_SerialNumber,
					Picture_URL:this.Specifications.Picture_URL,
					Specifications_Name:this.Specifications.Specifications_Name,
					Sales_Unit_Price:this.Specifications.Sales_Unit_Price,
					Browsing_Date:DateTime()
				}]
				await generalSave({Data:JSON.stringify({Add:{business_browsing_history}})});
			},
			countTimer(){//活动倒计时
				let obj = this.Article.article_specifications[this.active];//结束时间
				let End_Date = obj.Children.End_Date;
				End_Date = End_Date.replaceAll('-','/');//ios适配
				let {day, h, m ,s} = getCountDown(End_Date);//获取倒计时天、时、分、秒
				this.timer.d = day;
				this.timer.h = h;
				this.timer.m = m;
				this.timer.s = s;
			},
			scroll(e) {//监听页面滚动，滚动1000以上时显示"回到顶部"按钮
				if (e.detail.scrollTop >= 1000) {
					this.btn[0].isShow = true;
				} else {
					this.btn[0].isShow = false;
					this.scrollIntoViewId = "";
				}
			},
			handleBtn(title) {
				//点击屏幕左侧悬浮按钮或底部"首页"、"客服"按钮后对应操作
				if (title == "top") {//回到页面顶部
					this.scrollIntoViewId = title;
				} 
				// else if (title == "serve") {//进入"客服"页
				// 	uni.navigateTo({
				// 		url: "/pages/service/service",
				// 	});
				// } 
				else if (title == "car") {//进入"购物车"页
					uni.redirectTo({
						url: "/pages/index/shopCart",
					});
				} else if (title == "index") {//进入"首页"
					this.setBASEQuery({});
					this.setBASEPath(this.HOME_Page);
					uni.navigateTo({
						url: "/pages/index/index",
					});
				}
			},
			handleBuy(title) {
				//点击"立即购买"或"加入购物车"
				this.showMask = !this.showMask;
				if (title == "car") {
					this.mask = "car";
				} else {
					this.mask = "buy";
				}
			},
			changeIndicatorDots(e) {
				//每次轮播修改轮播图数--1/4
				this.current = e.detail.current + 1 + "/" + this.Swiper.length;
			},
			carouselChart() {
				//轮播图属性函数
				this.$nextTick(() => {
					//渲染完成后再执行
					uni.createSelectorQuery().in(this).select("#swiper").boundingClientRect((data) => {
						this.swiperWidth = data.width;
					}).exec();
				});
			},
			onAddress() {
				//跳转到地址列表
				uni.navigateTo({
					url: "/pages/delivery/address?is=select",
				});
			},
			changeTab(obj,item){//切换规格
				obj.Children.business_article_group_detail.forEach(item=>{
					item.isSelect = false;
				})
				item.isSelect = true;
				if(this.form.Activity_SerialNumber){
					this.countTimer();
				}
			},
			submitForm(){//提交
				if(this.mask == "buy"){
					let obj = {
						Activity_SerialNumber:this.Activity?this.Activity.Activity_SerialNumber:'',
						Article_SerialNumber:this.Article.Article_SerialNumber,
						Article_Name:this.Article.Article_Name,
						Brand_SerialNumber:this.Article.Brand_SerialNumber,
						Category_SerialNumber:this.Article.Category_SerialNumber,
						Series_SerialNumber:this.Article.Series_SerialNumber,
						Item_SerialNumber:this.Article.Item_SerialNumber,
						Unify_Unit_Price:this.Article.Unify_Unit_Price,
						Unit_Price:this.Article.Unit_Price,
						Picture_URL:this.Article.Picture_URL,
						Brand_Name:'',
						Activity_Name:this.Activity?this.Activity.Activity_Name:'',
						Specifications_Name:this.Specifications.Specifications_Name,
						Weight:this.Specifications.Weight,
						Weight_Unit:this.Specifications.Weight_Unit,
						Specifications_Picture_URL:this.Specifications.Picture_URL,
						Supplier_Article_SerialNumber:this.Specifications.Supplier_Article_SerialNumber,
						Supplier_SerialNumber:this.Article.Supplier_SerialNumber,
						Execute_Stock_SerialNumber:this.Specifications.Execute_Stock_SerialNumber,
						Stock_Remain:this.Specifications.Stock_Remain,
						Store_SerialNumber:'',
						Cash_Point:this.Activity?this.Activity.Cash_Point:'',
						Sales_Point:this.Activity?this.Activity.Sales_Point:'',
						Quantity:this.Quantity,
						Sales_Unit_Price_Stock_SerialNumber:this.Specifications.Execute_Stock_SerialNumber,
						Sales_Unit_Price:this.Activity?this.Activity.Activity_Unit_Price:this.Specifications.Sales_Unit_Price,
						Deduction_Type:this.Activity?this.Activity.Deduction_Type:'0',
						Combination:this.Activity?this.Activity.Combination:'',
						Deduction_Limit:this.Activity?this.Activity.Deduction_Limit:'0',
					}
					uni.navigateTo({
						url: "/pages/index/submitOrder?Article="+encodeURIComponent(JSON.stringify([obj])),
					});
				} else {//添加到购物车
					if(!this.loading){
						this.loading = true;
						this.generalQueryByTableName({
							TableName: 'business_shopping_trolley',
							Condition: "Row_Status='0' and Open_ID='"+this.Open_ID 
							+ "' and Supplier_Article_SerialNumber='" + this.Specifications.Supplier_Article_SerialNumber 
							+ "' and Activity_SerialNumber='" + (this.Activity?this.Activity.Activity_SerialNumber:'') + "'"
						},async (data)=>{
							const res = await addShoppingTrolley({
								Data:JSON.stringify(shoppingTrolleyJSON(data,this.Quantity,this.Open_ID,this.Specifications.Supplier_Article_SerialNumber,this.Activity?this.Activity.Activity_SerialNumber:''))
							});
							if(res.Status == 'success'){
								uni.showToast({
									title:'已加入购物车',
									icon:'none'
								})
								this.ShopCartQuantity();
								this.showMask = false;
							}else{
								uni.showToast({
									title:'系统繁忙',
									icon:'none'
								})
							}
							this.loading = false;
						})
					}
				}
			},
			async generalQueryByTableName(Data,callback){//通用查询
				callback(await generalQueryByTableName(Data));
			},
		},
	};
</script>

<style lang="scss">
	#shareBtn {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		opacity: 0;
	}

	.current {
		background-color: rgba(0, 0, 0, 0.5);
		position: absolute;
		bottom: 150rpx;
		right: 25rpx;
		justify-content: space-around;
	}

</style>